package com.huan.service.impl;

import com.huan.VO.BlogUserLoginVo;
import com.huan.VO.UserInfoVo;
import com.huan.domain.AppHttpCodeEnum;
import com.huan.domain.ResponseResult;
import com.huan.domain.entity.User;
import com.huan.domain.entity.loginuser;
import com.huan.security.exception.SystemException;
import com.huan.service.BlogLoginService;
import com.huan.utils.BeanCopyUtil;
import com.huan.utils.JwtUtil;
import com.huan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;
@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        loginuser loginuser = (loginuser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginuser.getUser().getId().toString());
        redisCache.setCacheObject("userid:"+loginuser.getUser().getId().toString(),loginuser);
        UserInfoVo infoVo = BeanCopyUtil.resultVO(loginuser.getUser(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt, infoVo);
        ResponseResult result = ResponseResult.okResult(blogUserLoginVo);
        return result;
    }

    @Override
    public ResponseResult logout() {
//        获取userid，并且将获取到的id在redis中删除
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        loginuser loginuser = (com.huan.domain.entity.loginuser) authentication.getPrincipal();
        Long id = loginuser.getUser().getId();
        String s = id.toString();
        boolean b = redisCache.deleteObject("userid:" + s);
        if (!b){
            throw  new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
        }

        return ResponseResult.okResult(200,"操作成功");
    }
}





















